package com.lechi.web.runner;

import com.lechi.web.service.IIotDeviceCmdService;
import com.lechi.web.service.ISchedulerService;
import com.lechi.web.system.domain.IotDeviceCmdSchedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目启动后添加定时轮训任务
 */
@Slf4j
@Order(6)
@Component()
public class StartSendCmdSchedule implements CommandLineRunner {

    @Autowired
    private IIotDeviceCmdService iotDeviceCmdService;

    @Autowired
    private ISchedulerService iSchedulerService;

    @Async
    public void run(String... args) {
        Long deviceId = args.length != 0 ? Long.parseLong(args[0]) : null;
        List<IotDeviceCmdSchedule> iotDeviceList = iotDeviceCmdService.selectIotDeviceCmdListForSchedule(deviceId);
        Map<Long, List<Map<String, String>>> scheduleMap = new HashMap<>();
        iotDeviceList.forEach(iotDeviceCmdSchedule -> {
            if (ObjectUtils.isEmpty(scheduleMap.get(iotDeviceCmdSchedule.getPeriod()))) {
                List<Map<String, String>> list = new ArrayList<>();
                Map<String, String> snCmdMap = new HashMap<>();
                snCmdMap.put(iotDeviceCmdSchedule.getDeviceSn(), iotDeviceCmdSchedule.getCmd());
                list.add(snCmdMap);
                scheduleMap.put(iotDeviceCmdSchedule.getPeriod(), list);
            } else {
                List<Map<String, String>> list = scheduleMap.get(iotDeviceCmdSchedule.getPeriod());
                Map<String, String> snCmdMap = new HashMap<>();
                snCmdMap.put(iotDeviceCmdSchedule.getDeviceSn(), iotDeviceCmdSchedule.getCmd());
                list.add(snCmdMap);
                scheduleMap.put(iotDeviceCmdSchedule.getPeriod(), list);
            }
        });
        scheduleMap.keySet().forEach(period -> {
            iSchedulerService.removeJob(String.valueOf(period));
            List<Map<String, String>> list = scheduleMap.get(period);
            iSchedulerService.addDynamicJob(String.valueOf(period), list);
        });
    }
}


